<template>
  <div id="examPage">
    <div style="display: flex; justify-content: space-between">
      <!-- 搜索栏 -->
      <a-form layout="inline" :model="searchParam" @finish="doSearch">
        <a-form-item label="考试名称">
          <a-input v-model:value="searchParam.examName" placeholder="请输入考试名称" allow-clear />
        </a-form-item>
        <a-form-item label="课程名称">
          <a-input
            v-model:value="searchParam.courseName"
            placeholder="请输入课程名称"
            allow-clear
          />
        </a-form-item>
        <a-form-item label="班级名称">
          <a-input v-model:value="searchParam.className" placeholder="请输入班级名称" allow-clear />
        </a-form-item>
        <a-form-item label="考试类型">
          <a-select v-model:value="searchParam.examType" style="width: 120px">
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="必修">期中考试</a-select-option>
            <a-select-option value="选修">期末考试</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" html-type="submit"> 搜索 </a-button>
        </a-form-item>
      </a-form>
      <a-button type="primary" size="large" @click="showAddModel">新增考试</a-button>
    </div>
    <div style="margin-bottom: 32px"></div>
    <!-- 表格 -->
    <a-table
      :columns="columns"
      :data-source="dataList"
      :pagination="pagination"
      @change="doTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'startTime'">
          {{ dayjs(record.startTime).format('YYYY-MM-DD HH-mm-ss') }}
        </template>
        <template v-if="column.dataIndex === 'endTime'">
          {{ dayjs(record.endTime).format('YYYY-MM-DD HH-mm-ss') }}
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space>
            <a-button type="primary" @click="showUpdateModel(record.id)">修改</a-button>
            <a-button type="primary" danger @click="doDelete(record.id)">删除</a-button>
          </a-space>
        </template>
      </template>
    </a-table>
    <a-modal v-model:open="addModel" title="添加考试" @ok="doAdd">
      <div style="height: 16px"></div>
      <a-form
        :model="formDataAdd"
        name="addExam"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
      >
        <a-form-item
          label="考试名称"
          name="examName"
          :rules="[{ required: true, message: '请输入考试名称' }]"
        >
          <a-input v-model:value="formDataAdd.examName" />
        </a-form-item>
        <a-form-item label="课程名称" name="courseName">
          <a-select v-model:value="formDataAdd.courseId" placeholder="请选择课程">
            <a-select-option v-for="item in courseList" :key="item.id" :value="item.id">{{
              item.courseName
            }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="班级名称" name="className">
          <a-select v-model:value="formDataAdd.classId" placeholder="请选择班级">
            <a-select-option v-for="item in studentGroupList" :key="item.id" :value="item.id">{{
              item.className
            }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="考试类型" name="examType">
          <a-select v-model:value="formDataAdd.examType">
            <a-select-option v-for="item in examTypeList" :key="item" :value="item">{{
              item
            }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="开始时间" name="startTime">
          <a-date-picker v-model:value="formDataAdd.startTime" show-time placeholder="选择时间" />
        </a-form-item>
        <a-form-item label="结束时间" name="endTime">
          <a-date-picker v-model:value="formDataAdd.endTime" show-time placeholder="选择时间" />
        </a-form-item>
        <a-form-item label="考试地点" name="examPlace">
          <a-input v-model:value="formDataAdd.examPlace" />
        </a-form-item>
        <a-form-item label="总分" name="totalScore">
          <a-input-number v-model:value="formDataAdd.totalScore" :min="1" :max="150" />
        </a-form-item>
        <a-form-item label="备注信息" name="remarks">
          <a-textarea v-model:value="formDataAdd.remarks" />
        </a-form-item>
      </a-form>
    </a-modal>
    <a-modal v-model:open="updateModel" title="修改考试信息" @ok="doUpdate">
      <div style="height: 16px"></div>
      <a-form
        :model="formDataUpdate"
        name="updateExam"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
      >
        <a-form-item
          label="考试名称"
          name="examName"
          :rules="[{ required: true, message: '请输入考试名称' }]"
        >
          <a-input v-model:value="formDataUpdate.examName" />
        </a-form-item>
        <a-form-item label="课程名称" name="courseName">
          <a-select v-model:value="formDataUpdate.courseId" placeholder="请选择课程">
            <a-select-option v-for="item in courseList" :key="item.id" :value="item.id">{{
                item.courseName
              }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="班级名称" name="className">
          <a-select v-model:value="formDataUpdate.classId" placeholder="请选择班级">
            <a-select-option v-for="item in studentGroupList" :key="item.id" :value="item.id">{{
                item.className
              }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="考试类型" name="examType">
          <a-select v-model:value="formDataUpdate.examType">
            <a-select-option v-for="item in examTypeList" :key="item" :value="item">{{
                item
              }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="开始时间" name="startTime">
          <a-date-picker v-model:value="startDatejs" show-time placeholder="选择时间" />
        </a-form-item>
        <a-form-item label="结束时间" name="endTime">
          <a-date-picker v-model:value="endDatejs" show-time placeholder="选择时间" />
        </a-form-item>
        <a-form-item label="考试地点" name="examPlace">
          <a-input v-model:value="formDataUpdate.examPlace" />
        </a-form-item>
        <a-form-item label="总分" name="totalScore">
          <a-input-number v-model:value="formDataUpdate.totalScore" :min="1" :max="150" />
        </a-form-item>
        <a-form-item label="备注信息" name="remarks">
          <a-textarea v-model:value="formDataUpdate.remarks" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue'
import dayjs from 'dayjs'
import { message } from 'ant-design-vue'
import {
  addExamUsingPost,
  deleteExamUsingPost,
  getExamByIdUsingGet,
  listExamByPageUsingPost,
  updateExamUsingPost,
} from '@/api/examController.ts'
import { listStudentGroupUsingPost } from '@/api/studentGroupController.ts'
import { listCourseUsingPost } from '@/api/courseController.ts'

const addModel = ref<boolean>(false)
const updateModel = ref<boolean>(false)

const columns = [
  {
    title: '考试名称',
    dataIndex: 'examName',
  },
  {
    title: '课程名称',
    dataIndex: 'courseName',
  },
  {
    title: '班级名称',
    dataIndex: 'className',
  },
  {
    title: '考试类型',
    dataIndex: 'examType',
  },
  {
    title: '开始时间',
    dataIndex: 'startTime',
  },
  {
    title: '结束时间',
    dataIndex: 'endTime',
  },
  {
    title: '考试地点',
    dataIndex: 'examPlace',
  },
  {
    title: '操作',
    key: 'action',
  },
]

// 定义数据
const dataList = ref<API.Exam[]>([])
const total = ref(0)

const examTypeList = ['期中考试', '期末考试']

// 搜索条件
const searchParam = reactive<API.ExamQueryRequest>({
  current: 1,
  pageSize: 10,
  examName: '',
  courseName: '',
  className: '',
  examType: '',
  examPlace: '',
})

// 分页参数
const pagination = computed(() => {
  return {
    current: searchParam.current,
    pageSize: searchParam.pageSize,
    total: total.value,
    showSizeChanger: true,
    showTotal: (total: number) => `共${total}条`,
  }
})

const doTableChange = (page: any) => {
  searchParam.current = page.current
  searchParam.pageSize = page.pageSize
  fetchData()
}

// 获取数据
const fetchData = async () => {
  const res = await listExamByPageUsingPost({
    ...searchParam,
  })
  if (res.data.code === 0 && res.data.data) {
    dataList.value = res.data.data.records ?? []
    total.value = res.data.data.total ?? 0
  } else {
    message.error('获取数据失败' + res.data.message)
  }
}

const studentGroupList = ref<API.StudentGroup[]>([])
const fechStudentGroupList = async () => {
  const res = await listStudentGroupUsingPost({})
  if (res.data.code === 0 && res.data.data) {
    studentGroupList.value = res.data.data
  } else {
    message.error('获取数据失败' + res.data.message)
  }
}
const courseList = ref<API.Course[]>([])
const fechCourseList = async () => {
  const res = await listCourseUsingPost({})
  if (res.data.code === 0 && res.data.data) {
    courseList.value = res.data.data
  } else {
    message.error('获取数据失败' + res.data.message)
  }
}

// 页面加载时获取数据，请求一次
onMounted(() => {
  fetchData()
  fechStudentGroupList()
  fechCourseList()
})

const doSearch = () => {
  // 重置页码
  searchParam.current = 1
  fetchData()
}

const doDelete = async (id: number) => {
  if (!id) {
    return
  }
  const res = await deleteExamUsingPost({ id: id })
  if (res.data.code === 0) {
    message.success('删除成功')
    // 刷新数据
    fetchData()
  } else {
    message.error('删除失败')
  }
}

const formDataAdd = reactive<API.ExamAddRequest>({
  examName: '',
  courseId: undefined,
  courseName: '',
  classId: undefined,
  className: '',
  examType: '',
  startTime: '',
  endTime: '',
  examPlace: '',
  totalScore: 100,
  remarks: '',
})
const formDataUpdate = ref<API.ExamUpdateRequest>({
  examName: '',
  courseId: undefined,
  courseName: '',
  classId: undefined,
  className: '',
  examType: '',
  startTime: '',
  endTime: '',
  examPlace: '',
  totalScore: 100,
  remarks: '',
})

const startDatejs = ref(dayjs())
const endDatejs = ref(dayjs())
watch(startDatejs, (newValue) => {
  formDataUpdate.value.startTime = newValue.toString()
})
watch(endDatejs, (newValue) => {
  formDataUpdate.value.endTime = newValue.toString()
})

const doUpdate = async () => {
  const res = await updateExamUsingPost({
    ...formDataUpdate.value,
  })
  if (res.data.code === 0 && res.data.data !== null) {
    message.success('更新成功')
    fetchData()
    updateModel.value = false
  } else {
    message.error('更新失败, ' + res.data.message)
  }
}

const doAdd = async () => {
  const res = await addExamUsingPost({
    ...formDataAdd,
  })
  if (res.data.code === 0 && res.data.data !== null) {
    message.success('添加成功')
    fetchData()
    addModel.value = false
  } else {
    message.error('添加失败, ' + res.data.message)
  }
}

const showAddModel = () => {
  formDataAdd.examName = ''
  formDataAdd.courseId = undefined
  formDataAdd.courseName = ''
  formDataAdd.classId = undefined
  formDataAdd.className = ''
  formDataAdd.examType = ''
  formDataAdd.startTime = ''
  formDataAdd.endTime = ''
  formDataAdd.examPlace = ''
  formDataAdd.totalScore = 100
  formDataAdd.remarks = ''
  addModel.value = true
}

const showUpdateModel = async (id: number) => {
  const res = await getExamByIdUsingGet({ id })
  if (res.data.code === 0 && res.data.data !== null) {
    formDataUpdate.value = {
      ...res.data.data,
    }
    startDatejs.value = dayjs(res.data.data.startTime)
    endDatejs.value = dayjs(res.data.data.endTime)
    updateModel.value = true
  } else {
    message.error('获取数据失败, ' + res.data.message)
  }
}
</script>

<style scoped></style>
